package com.mall.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.mapper.SkuStockMapper;
import com.mall.model.domain.PmsSkuStock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class SkuStockService {

    @Autowired
    private SkuStockMapper skuStockMapper;

    /**
     * 批量更新sku库存信息
     *
     * @param pid
     * @param list
     */
    @Transactional
    public void batchUpdateByPid(Integer pid, List<PmsSkuStock> list) {
        //构建查询sku库存信息的queryWrapper
        LambdaQueryWrapper<PmsSkuStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(pid != null, PmsSkuStock::getProductId, pid);
//查询与pid相同的库存集合
        List<PmsSkuStock> pmsSkuStocks = skuStockMapper.selectList(queryWrapper);
        for (PmsSkuStock pmsSkuStock : pmsSkuStocks) {
            for (PmsSkuStock skuStock : list) {
                if(skuStock.getId().equals(pmsSkuStock.getId())){
                    skuStockMapper.updateById(skuStock);
                }
            }
        }
    }


    /**
     * 根据商品ID及sku编码模糊搜索sku库存
     *
     * @param pid
     * @param keyword
     * @return
     */
    public List<PmsSkuStock> querySkuByIdAndSkuCode(Integer pid, String keyword) {
        //构建查询sku库存信息的queryWrapper
        LambdaQueryWrapper<PmsSkuStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(pid != null, PmsSkuStock::getProductId, pid);
        queryWrapper.eq(!StringUtils.isEmpty(keyword), PmsSkuStock::getSkuCode, keyword);
        //调用skuStockMapper查询sku库存
        return skuStockMapper.selectList(queryWrapper);
    }
}
